'use strict';
//学生控制器
const xtpl = require('xtpl');
const path = require('path');
const moment = require('moment');
const fs = require('fs');
const mysql = require('../configs/database.js');
const baseCtr = require('./baseController.js');

module.exports.stuAdd = function(req, res) {
    // res.send('添加学生');
    mysql.table('class').select().then(function(data) {
        mysql.table('subject').select().then(function(subData) {
            xtpl.renderFile(
                path.join(__dirname, '../views/admin/student_add.html'), {
                    page: 'stuAdd',
                    clsList: data,
                    subList: subData
                },
                function(err, content) {
                    res.setHeader('Content-Type', 'text/html;charset=utf-8');
                    res.send(content);
                }
            )
        });

    }).catch(function(err) {
        console.log(err);
    });
}

module.exports.stuAddData = function(req, res) {
    console.log(req.body);
    // path.basename(req.files.sphoto.path)
    var photo = path.parse(req.files.sphoto.path).base;
    var where = `stu_name='${req.body.sname}' or stu_phone='${req.body.sphone}'`;
    mysql.table('student').field('stu_id').where(where).find().then(function(result) {

        if (JSON.stringify(result) == '{}') {
            var data = {
                class_id: req.body.sclass,
                stu_name: req.body.sname,
                stu_age: req.body.sage,
                stu_sex: req.body.sex,
                stu_phone: req.body.sphone,
                stu_time: Date.parse(req.body.stime) / 1000,
                stu_img: photo
            }

            mysql.table('student').add(data).then(function(stuId) {
                var sub = req.body.sub;
                var sdata = [];
                for (let i in sub) {
                    sdata.push({ stu_id: stuId, sub_id: sub[i] });
                }
                // console.log(sdata);
                mysql.table('student_subject_data').addAll(sdata).then(function() {
                    res.redirect('/admin/student/student_list');
                }).catch(function(err) {
                    console.log(err)
                });
            }).catch(function(err) {
                console.log(err);
            });
        } else {
            baseCtr.sendMsg('该学生已存在', res);
        }
    }).catch(function(err) {
        console.log(err);

    });
}

module.exports.stuList = function(req, res) {
    var where = req.query.stext != undefined ? { 'stu_name|stu_phone': ['LIKE', '%'+req.query.stext+'%'] } : 1;

    var pn = req.query.pn != undefined ? req.query.pn : 1;
    var limit = 3;
    var start = (pn - 1) * limit;
    // res.send('学生列表');
    mysql.table('student').where(where).join({
        table: 'class',
        join: 'left',
        on: ['class_id', 'class_id']
    }).limit(start, limit).select().then(function(data) {

        mysql.table('student').where(where).count('stu_id').then(function(total) {
            var pageArr = [];
            var totalPn = Math.ceil(total / limit);
            for (var i = 1; i <= totalPn; i++) {
                pageArr.push(i);
            }
            xtpl.renderFile(
                path.join(__dirname, '../views/admin/student_list.html'), {
                    page: 'stuList',
                    stuList: data,
                    pageArr: pageArr,
                    pn: parseInt(pn),
                    endPn: totalPn
                },
                function(err, content) {
                    // res.send(JSON.stringify({error:0,msg:'搜索成功'}));
                    res.setHeader('Content-Type', 'text/html;charset=utf-8');
                    res.send(content);
                }
            )
        }).catch(function(err) {
            console.log(err)
        });
    }).catch(function(err) {
        console.log(err)
    });
}

module.exports.stuStatus = function(req, res) {
    mysql.table('student').where({ stu_id: req.body.stu_id }).update({ stu_status: req.body.stu_status }).then(function(result) {
        if (JSON.stringify(result) != '{}') {
            // 成功登录
            res.send(JSON.stringify({ error: 0, msg: '修改成功' }))
        } else {
            res.send(JSON.stringify({ error: 1, msg: '修改错误' }))
        }
    });
}

module.exports.stuDelData = function(req, res) {
    var id = req.params.id;
    mysql.table('student_subject_data').where(`stu_id='${id}'`).delete().then(function(subRows) {
        mysql.table('student').where(`stu_id='${id}'`).delete().then(function(stuRows) {
            res.redirect('/admin/student/student_list');
        });
    });
}

module.exports.stuDelAllData = function(req, res) {
    var where = `stu_id in (${req.params.id})`;
    mysql.table('student_subject_data').where(where).delete().then(function(subRows) {
        mysql.table('student').where(where).delete().then(function(stuRows) {
            res.redirect('/admin/student/student_list');
        });
    });
}


module.exports.stuEdit = function(req, res) {
    mysql.table('class').select().then(function(clsData) {
        mysql.table('student').where({ stu_id: req.params.id }).find().then(function(stuData) {
            mysql.table('subject').select().then(function(subData) {
            	mysql.table('student_subject_data').where({ stu_id: req.params.id }).select().then(function(ssData) {
            		for(let i=0; i<subData.length; i++){
                        subData[i].issub = 0;
                        for(let j=0; j<ssData.length; j++){
                            if(subData[i].sub_id === ssData[j].sub_id){
                                subData[i].issub = 1;
                            }
                        }
                    }
                    
                    // console.log(subData);
	                // 转换时间（记得时间戳是：毫秒）
	                stuData.stu_time = moment(stuData.stu_time * 1000).format('YYYY-MM-DD');
	                // 显示视图
	                xtpl.renderFile(
	                    path.join(__dirname, '../views/admin/student_edit.html'), // 加载视图文件
	                    {
	                        page: 'stuEdit',
	                        clsList: clsData,
	                        stuData: stuData,
	                        subList: subData,
	                    },
	                    function(err, content) {
	                        res.setHeader('Content-Type', 'text/html;charset=utf-8');
	                        res.send(content);
	                    }
	                );
            	});
            }).catch(function(err) {
                //err为具体的错误信息
                console.log(err) // 命令行显示(方便调试)
            });
        });

    }).catch(function(err) {
        //err为具体的错误信息
        console.log(err) // 命令行显示(方便调试)
    });
}

module.exports.stuEditData = function(req, res) {
    var where = `stu_id!='${req.params.id}' and (stu_name='${req.body.stu_name}' or stu_phone='${req.body.stu_phone}')`;
    mysql.table('student').field('stu_id').where(where).find().then(function(result) {
        if (JSON.stringify(result) == '{}') {
            var data = {
                stu_name: req.body.stu_name,
                stu_age: req.body.stu_age,
                stu_sex: req.body.stu_sex,
                stu_phone: req.body.stu_phone,
                stu_time: Date.parse(req.body.stu_time) / 1000,
                class_id: req.body.class_id,
            }

            if (req.files.stu_img.size == 0) {
                fs.unlink(req.files.stu_img.path, function() {});
            } else {
                data.stu_img = path.parse(req.files.stu_img.path).base;
            }
            // console.log(data)
            mysql.table('student').where({ stu_id: req.params.id }).update(data).then(function() {
                // console.log('修改成功');
                mysql.table('student_subject_data').where({ stu_id: req.params.id }).delete().then(function(subRows) {
                    
                    var sub = req.body.sub;
                    var sdata = [];
                    for (let i in sub) {
                        sdata.push({ stu_id: req.params.id, sub_id: sub[i] });
                    }
                    mysql.table('student_subject_data').addAll(sdata).then(function() {
                        res.redirect('/admin/student/student_list');
                    }).catch(function(err) {
                        console.log(err)
                    });
                });
            }).catch(function(err) {
                console.log(err)
            })
        } else {
            baseCtr.sendMsg('该学生已存在', res);
        }
    }).catch(function(err) {
        console.log(err)
    })
}